﻿package auto.main;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;

import org.apache.ibatis.session.SqlSession;
import org.openqa.selenium.os.WindowsUtils;


import auto.vpn.Vpn;
import baseDao.RangeLoginDao;
import baseDao.RecordDao;
import baseDao.TaskListDao;
import deta.Vp;
import entity.Adv;
import entity.Record;
import entity.TaskList;
import entity.User;
import swing.Index;
import swing.Login;
import util.GetSqlSession;
import util.IPAddress;
import util.LogUtil;
/**
 * 
 * @author 浏览器处理类(入口)
 *
 */
public class Test {
	 public static boolean exit = true; 
	 public static boolean ex=true;
	 public static int id;
	 public static int userId;
	public static int browserStatus;
	static Thread thread;
	static Integer listid;//列表中的id
	static int j;
	public	static boolean ab=false;
	public static List<TaskList> stall;
	public static void startAuto(List<TaskList> all,JRadioButton s3,JRadioButton s2,JRadioButton s1,JRadioButton s6,JButton SatrtMission,List<Integer> list){
		stall=all;
	
		 thread= new Thread() {
			@Override
			public synchronized void run() {
				
				
			for(int i=0;i<all.size();i++){
				Vpn.vpnCount=0;
				System.out.println("重新开始下一条");
				
			
				j=i;
				
				
				
				
				
				
				
				
				
				
				boolean fi=true;
				listid = list.get(i);
				User validate = RangeLoginDao.validate(Login.us);
				long expireTime = validate.getExpireTime();
				long currentTimeMillis = System.currentTimeMillis();
				if(expireTime<currentTimeMillis){
					System.err.println(Login.us);
					JOptionPane.showMessageDialog(null, "您的账号已过期,请及时续费!!!");
					System.exit(0);
				}
				
				
				id=all.get(i).getTaskId();
				 userId = all.get(i).getUserId();
				
				 browserStatus = 0;
				// 调用浏览器的入口方法
				if (s1.isSelected()) {
					browserStatus = 1;
					System.out.println("谷歌");
				} else if (s2.isSelected()) {
					browserStatus = 2;
					System.out.println("火狐");
				} else if (s3.isSelected()) {
					browserStatus = 3;
					System.out.println("IE");
				}else if(s6.isSelected()){
					Random random = new Random();
					browserStatus = random.nextInt(2)+1;
				}
				
				
				
				
				
				SqlSession session = GetSqlSession.getSession();
				TaskListDao taskDao = session.getMapper(TaskListDao.class);
				System.out.println(i+"----------------------");
				
				
				if(1==all.get(i).getTaskType()){
					while(exit){
						System.out.println(System.currentTimeMillis()+"当前系统时间");
					if(all.get(i).getTimer()<=System.currentTimeMillis()){
						System.out.println(all.get(i).getTimer()+"后台过来的时间");
						System.out.println(System.currentTimeMillis()+"当前系统时间");
						ex=true;
						break;
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				}else{
						while (exit) {

							System.out.println("break了吗");
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							System.out.println(System.currentTimeMillis()
									+ "当前系统时间");
							System.out.println(all.get(i).getTimer()
									- System.currentTimeMillis() + "时间差");
							System.out
									.println(all.get(i).getTimer() + "后台传入时间");

							if (all.get(i).getTimer()
									- System.currentTimeMillis() < 0) {
								session = GetSqlSession.getSession();
								taskDao = session.getMapper(TaskListDao.class);
								fi = false;
								LogUtil.logInsert(LogUtil.RED,
										"任务编号" + list.get(i) + "执行异常");
								TaskList s = new TaskList();
								s.setTaskId(all.get(i).getTaskId());

								s.setExecutingState("异常");

								taskDao.updateZt(s);

								// 修改热词表中的状态(判断当前任务是否成功)
								// System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
								// if("异常"==all.get(i).getExecutingState()){
								RecordDao recordDao = session
										.getMapper(RecordDao.class);
								Record record1 = new Record();
								record1.setUserId(Login.getUser().getId());
								record1.setTaskId(id);
								List<Record> recordList = recordDao
										.selectByTimeWhere(record1);
								if (recordList.size() > 0) {
									recordList.get(recordList.size() - 1)
											.setState(2);// 2------代表失败
									recordDao.update(recordList.get(recordList
											.size() - 1));
								}
								Index.refresh(Index.table, all.get(i)
										.getUserId());
								// }
								session.commit();
								session.close();
								ex = false;
								break;
							}
					
					
					
					
					if(all.get(i).getTimer()-System.currentTimeMillis()<2000){
						
						System.out.println(all.get(i).getTimer()+"后台过来的时间");
						System.out.println(System.currentTimeMillis()+"当前系统时间");
						ex=true;
						break;
						
						
						
					}
					
					
					
					
				}
					
				}




				if(ex){
					System.out.println("进 了  ex");
					if(exit){
						System.out.println("进 了  exit");
						LogUtil.logInsert(LogUtil.BLACK, "任务编号:"+list.get(i)+"--->开始执行");
				System.out.println(all.get(i).getYourWebsite());
				//数据
				Adv adv = new Adv(0,all.get(i).getYourWebsite(), browserStatus, 2, all.get(i).getAdvertisingOptions(),all.get(i).getYourWebsite(),all.get(i).getArrivalMode());
					//DriverService service = null;
					//WebDriver driver = null;
					boolean cflag = true;
					boolean  sflag = true;
					//指定浏览器
					int rdnum = browserStatus;
					if(browserStatus==0){
						rdnum = new Random().nextInt(3) + 1;
					}
					try {
						Vpn.vpnCount=0;
						//开启vpn
						if("vpn".equals(all.get(i).getSwitchingIP())&&exit){
							
							sflag = Vpn.connAdsl("vpntest", Login.getVP().getAcNu(),Login.getVP().getPw());
							//判断vpn是否重复
							 IPAddress ipAddress = new  IPAddress();
							 //有可能有问题*****
								if(ipAddress.outIp()){
									System.out.println("***************vpn出问题了.....");
									cflag = Vpn.cutAdsl("vpntest");
								}
						}
						
					
						if (cflag && sflag ) {
							System.out.println(cflag+" "+sflag+" "+Vpn.vpnCount+"连接次数");
								if(Vpn.vpnCount<5){
									
								}else{
									System.out.println("vpn连接超时........3次");
									return;
								}
								System.out.println("vpn22222222222222");
							try {
								//as.select(driver, all.get(i).getYourWebsite(),all.get(i).getAdvertisingOptions());
								//as.selectAdv(driver, adv,service);
								Vp v=new Vp();
								v.test(all.get(i),browserStatus,list.get(i));
								Thread.sleep(18000);
								//改变开始任务的按钮的值
								//SatrtMission.setEnabled(true);
								//SatrtMission.setText("开始任务");
							} catch (Exception e) {
								fi=false;
								LogUtil.logInsert(LogUtil.RED, "任务编号"+list.get(i)+"执行异常");
								TaskList s = new TaskList();
								s.setTaskId(all.get(i).getTaskId());
								
									s.setExecutingState("异常");
								
								 taskDao.updateZt(s);
								 
								//修改热词表中的状态(判断当前任务是否成功)
									//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
									//if("异常"==all.get(i).getExecutingState()){
										RecordDao recordDao = session.getMapper(RecordDao.class);
										Record record1 =new Record();
										record1.setUserId(Login.getUser().getId());
										record1.setTaskId(id);
										List<Record> recordList = recordDao.selectByTimeWhere(record1);
										if(recordList.size()>0){
											recordList.get(recordList.size()-1).setState(2);//2------代表失败
											recordDao.update(recordList.get(recordList.size()-1));
										}
										Index.refresh(Index.table, all.get(i).getUserId());
									//}
								session.commit();
								session.close();
								e.printStackTrace();
							} finally {
								//as.close(driver, service);
							}
						}

					} catch (Exception e) {
						fi=false;
						LogUtil.logInsert(LogUtil.RED, "任务编号"+list.get(i)+"执行异常");
						TaskList s = new TaskList();
						s.setTaskId(all.get(i).getTaskId());
						
							s.setExecutingState("异常");
						
						 taskDao.updateZt(s);
					
						//修改热词表中的状态(判断当前任务是否成功)
							//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
							//if("异常"==all.get(i).getExecutingState()){
								RecordDao recordDao = session.getMapper(RecordDao.class);
								Record record1 =new Record();
								record1.setUserId(Login.getUser().getId());
								record1.setTaskId(id);
								List<Record> recordList = recordDao.selectByTimeWhere(record1);
								if(recordList.size()>0){
									recordList.get(recordList.size()-1).setState(2);//2------代表失败
									recordDao.update(recordList.get(recordList.size()-1));
								}
								Index.refresh(Index.table, all.get(i).getUserId());
							//}
						session.commit();
						session.close();
						e.printStackTrace();
					} finally {
						if(Vpn.vpnCount>5){
							
							clsta(SatrtMission);
							
						}
						/*try {
							if (sflag&&exit) {
								
								System.out.println("从新连接vpn.....");
								if("vpn".equals(all.get(i).getSwitchingIP())){
									cflag = Vpn.cutAdsl("vpntest");
								}
							}

						} catch (Exception e) {*/
						/*	LogUtil.logInsert(LogUtil.RED, "任务编号"+list.get(i)+"执行异常");
							fi=false;
							TaskList s = new TaskList();
							s.setTaskId(all.get(i).getTaskId());
							
								s.setExecutingState("异常");
							
							 taskDao.updateZt(s);
						
							//修改热词表中的状态(判断当前任务是否成功)
								//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
								//if("异常"==all.get(i).getExecutingState()){
									RecordDao recordDao = session.getMapper(RecordDao.class);
									Record record1 =new Record();
									record1.setUserId(Login.getUser().getId());
									record1.setTaskId(id);
									List<Record> recordList = recordDao.selectByTimeWhere(record1);
									if(recordList.size()>0){
										recordList.get(recordList.size()-1).setState(2);//2------代表失败
										recordDao.update(recordList.get(recordList.size()-1));
									}
									
									Index.refresh(Index.table, all.get(i).getUserId());
								//}
							session.commit();
							session.close();*/
						//	e.printStackTrace();
						//}
					}
					System.out.println("执行到了fi");
					if(fi){
						LogUtil.logInsert(LogUtil.GREEN, "任务编号:"+list.get(i)+"--->执行成功");
					}
					
				}else{
					
					exit=true;
					break;
				}


				}
				//杀掉进程
				if(browserStatus==1){
					//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
				       WindowsUtils.killByName("chrome.exe");
				}else if(browserStatus==2){
					//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
				       WindowsUtils.killByName("firefox.exe");
				}else if(browserStatus==3){
					 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
				       WindowsUtils.killByName("iexplore.exe");
				}
				

			  
				
			  
				
			}
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
		
			
			if(ex){
			SatrtMission.setEnabled(true);
			SatrtMission.setText("开始任务");
			}
			
			if(ab){
				System.out.println("ppppp------"+ab);
				abnormal(all,s3,s2,s1,s6,SatrtMission,list);
			}else{
				//Clock.threadps.stop();
				//SatrtMission.setEnabled(true);
				//SatrtMission.setText("开始任务");
			}
					
			
			}
			
			
			
			
			
		};
		thread.start();
		/*try {
			thread.wait();
		} catch (InterruptedException e1) {
			System.out.println("线程等待失败.....");
			e1.printStackTrace();
		}*/
		
		
		if(!exit) {
			thread.stop();
			SqlSession session = GetSqlSession.getSession();
			TaskListDao taskDao = session.getMapper(TaskListDao.class);
			TaskList s = new TaskList();
			s.setTaskId(id);
			
				s.setExecutingState("异常");
			
			 taskDao.updateZt(s);
			
			//修改热词表中的状态(判断当前任务是否成功)
				//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
				//if("异常"==all.get(i).getExecutingState()){
					RecordDao recordDao = session.getMapper(RecordDao.class);
					Record record1 =new Record();
					record1.setUserId(Login.getUser().getId());
					record1.setTaskId(id);
					List<Record> recordList = recordDao.selectByTimeWhere(record1);
					if(recordList.size()>0){
						recordList.get(recordList.size()-1).setState(2);//2------代表失败
						recordDao.update(recordList.get(recordList.size()-1));
					}
				//}
			session.commit();
			session.close();
			Index.refresh(Index.table, userId);
			 try {
			//杀掉进程
			if(browserStatus==1){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
			       WindowsUtils.killByName("chrome.exe");
			      
					Vpn.executeCmd("taskkill /IM chrome.exe");
				
			}else if(browserStatus==2){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
			       WindowsUtils.killByName("firefox.exe");
			       Vpn.executeCmd("taskkill /IM firefox.exe");
			}else if(browserStatus==3){
				 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
			       WindowsUtils.killByName("iexplore.exe");
			       Vpn.executeCmd("taskkill /IM iexplore.exe");
			}
			 } catch (Exception e) {
					System.out.println("出异常了*****************");
					
				}
		}
	

		
		
	}
	
	
	
public	static	void  abnormal(List<TaskList> allss,JRadioButton s3,JRadioButton s2,JRadioButton s1,JRadioButton s6,JButton SatrtMission,List<Integer> list){
	System.out.println("进这个方法了..............");	
	Index.SatrtMission.setEnabled(false);
	Index.SatrtMission.setText("执行中....");
		System.out.println("---------------------------------------");
			
			SqlSession session = GetSqlSession.getSession();
			TaskListDao dao = session.getMapper(TaskListDao.class);
			List<TaskList> alls = dao.selectAll(Index.user.getId());
			System.out.println(alls.toString());
			if(alls.size() > 0){
				for(int i=0;i<alls.size();i++){
					if("异常".equals(alls.get(i).getExecutingState())){
						
						TaskList s = new TaskList();
						System.out.println(alls.get(i).getTaskId()+"///////////////////////////");
						s.setTaskId(alls.get(i).getTaskId());
						
							s.setExecutingState("未执行");
						
						dao.updateZt(s);
						
						Index.refresh(Index.table, Index.user.getId());
					}
					
				}
			}
			
			
			
			
			
			
				
			List<TaskList> all = dao.selectnonExecution(Index.user.getId());
			if (all.size() > 0) {
				list=new ArrayList<Integer>();
				for(int i=0;i<Index.table.getRowCount();i++){
					if("未执行".equals(((String)Index.table.getValueAt(i,2)))){
						list.add((Integer) Index.table.getValueAt(i, 0));
					}
				}
			
				Test.exit=true;
				ab=false;
				Clock.threadps.stop();
				Test.startAuto(all, s3,s2,s1,s6,SatrtMission,list);
				Clock.connect();
			} 
			
			
				
				session.close();
			
} 
			
			
			
			
	
			
			
		
public	static	void  abnormals(List<TaskList> allss,JRadioButton s3,JRadioButton s2,JRadioButton s1,JRadioButton s6,JButton SatrtMission,List<Integer> list){
	
	System.out.println("进这个方法了..............");	
	Index.SatrtMission.setEnabled(false);
	Index.SatrtMission.setText("执行中....");
		System.out.println("---------------------------------------");
			
		/*	SqlSession session = GetSqlSession.getSession();
			TaskListDao dao = session.getMapper(TaskListDao.class);
			List<TaskList> alls = dao.selectAll(Index.user.getId());
			System.out.println(alls.toString());
			if(alls.size() > 0){
				for(int i=0;i<alls.size();i++){
					if("异常".equals(alls.get(i).getExecutingState())){
						
						TaskList s = new TaskList();
						s.setTaskId(alls.get(i).getTaskId());
						
							s.setExecutingState("未执行");
						
						dao.updateZt(s);
						
						Index.refresh(Index.table, Index.user.getId());
					}
					
				}
			}*/
			
			
			
			
			
			
				
			//List<TaskList> all = dao.selectnonExecution(Index.user.getId());
			if (allss.size() > 0) {
				list=new ArrayList<Integer>();
				for(int i=0;i<Index.table.getRowCount();i++){
					if("未执行".equals(((String)Index.table.getValueAt(i,2)))){
						list.add((Integer) Index.table.getValueAt(i, 0));
					}
				}
			
				Test.exit=true;
				//Test.ab=true;
				//thread.stop();
				Test.startAuto(allss, s3,s2,s1,s6,SatrtMission,list);
			} 
			
			
				
//				session.close();
			
} 		
			
			
			
	
	
	public static void col() throws InterruptedException{
			//if(!exit) {
		//thread.stop();
			System.out.println("*********************");
			
			SqlSession session = GetSqlSession.getSession();
			TaskListDao taskDao = session.getMapper(TaskListDao.class);
			TaskList s = new TaskList();
			System.out.println(id+"----------------------------");
			s.setTaskId(id);
			
				s.setExecutingState("异常");
			
			 taskDao.updateZt(s);
			
			//修改热词表中的状态(判断当前任务是否成功)
				//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
				//if("异常"==all.get(i).getExecutingState()){
					RecordDao recordDao = session.getMapper(RecordDao.class);
					Record record1 =new Record();
					record1.setUserId(Login.getUser().getId());
					record1.setTaskId(id);
					System.out.println(id+"----------");
					List<Record> recordList = recordDao.selectByTimeWhere(record1);
					System.out.println(recordList.size());
					if(recordList.size()>0){
						Record record = recordList.get(recordList.size()-1);
						record.setState(2);//2------代表失败
						System.out.println(record.toString());
						recordDao.update(record);
					}
					
					//}
						session.commit();
						session.close();
						
				
				Index.refresh(Index.table,userId);
				
				LogUtil.logInsert(LogUtil.RED, "任务编号"+listid+"执行异常");
			
			 try {
			//杀掉进程
			if(browserStatus==1){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
			       WindowsUtils.killByName("chrome.exe");
			      
					Vpn.executeCmd("taskkill /IM chrome.exe");
					Vpn.executeCmd("taskkill /F /IM chromedriver_2.33.exe");
				
			}else if(browserStatus==2){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
			       WindowsUtils.killByName("firefox.exe");
			       Vpn.executeCmd("taskkill /IM firefox.exe");
			       Vpn.executeCmd("taskkill /F /IM geckodriver_0.19.exe");
			}else if(browserStatus==3){
				 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
			       WindowsUtils.killByName("iexplore.exe");
			       Vpn.executeCmd("taskkill /IM iexplore.exe");
			       Vpn.executeCmd("taskkill /F /IM IEDriverServer.exe");
			}
			 } catch (Exception e) {
					System.out.println("出异常了*****************");
					
				}
			 
			 
			 try {
					//杀掉进程
					if(browserStatus==1){
						//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
					       WindowsUtils.killByName("chrome.exe");
					      
							Vpn.executeCmd("taskkill /IM chrome.exe");
						
					}else if(browserStatus==2){
						//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
					       WindowsUtils.killByName("firefox.exe");
					       Vpn.executeCmd("taskkill /IM firefox.exe");
					}else if(browserStatus==3){
						 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
					       WindowsUtils.killByName("iexplore.exe");
					       Vpn.executeCmd("taskkill /IM iexplore.exe");
					}
					 } catch (Exception e) {
							System.out.println("出异常了*****************");
							
						}
			//  thread.wait(1000);
		
	}
	
	
	
	
	public static void  cls(){
		if(!exit) {
			
			System.out.println("*********************");
			
			SqlSession session = GetSqlSession.getSession();
			TaskListDao taskDao = session.getMapper(TaskListDao.class);
			TaskList s = new TaskList();
			System.out.println(id+"----------------------------");
			s.setTaskId(id);
			
				s.setExecutingState("异常");
			
			 taskDao.updateZt(s);
			
			//修改热词表中的状态(判断当前任务是否成功)
				//System.out.println(all.get(i).getExecutingState()+"--------判断当前任务是否成功---------");
				//if("异常"==all.get(i).getExecutingState()){
					RecordDao recordDao = session.getMapper(RecordDao.class);
					Record record1 =new Record();
					record1.setUserId(Login.getUser().getId());
					record1.setTaskId(id);
					System.out.println(id+"----------");
					List<Record> recordList = recordDao.selectByTimeWhere(record1);
					System.out.println(recordList.size());
					if(recordList.size()>0){
						Record record = recordList.get(recordList.size()-1);
						record.setState(2);//2------代表失败
						System.out.println(record.toString());
						recordDao.update(record);
					}
					
					//}
						session.commit();
						session.close();
						
					}
				Index.refresh(Index.table,userId);
				
				LogUtil.logInsert(LogUtil.RED, "任务编号"+listid+"执行异常");
		
			 try {
			//杀掉进程
			if(browserStatus==1){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
			       WindowsUtils.killByName("chrome.exe");
			      
					Vpn.executeCmd("taskkill /IM chrome.exe");
					Vpn.executeCmd("taskkill /F /IM chromedriver_2.33.exe");
				
			}else if(browserStatus==2){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
			       WindowsUtils.killByName("firefox.exe");
			       Vpn.executeCmd("taskkill /IM firefox.exe");
			       Vpn.executeCmd("taskkill /F /IM geckodriver_0.19.exe");
			}else if(browserStatus==3){
				 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
			       WindowsUtils.killByName("iexplore.exe");
			       Vpn.executeCmd("taskkill /IM iexplore.exe");
			       Vpn.executeCmd("taskkill /F /IM IEDriverServer.exe");
			}
			 } catch (Exception e) {
					System.out.println("出异常了*****************");
					
				}
				thread.stop();
		}
	
	
	
	public static void  clsta(JButton SatrtMission){
		
		SatrtMission.setEnabled(true);
		SatrtMission.setText("开始任务");
			System.out.println("调用了关闭线程的方法....");
			 //thread.stop();
			 try {
			//杀掉进程
			if(browserStatus==1){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有chrome浏览器
			       WindowsUtils.killByName("chrome.exe");
			      
					Vpn.executeCmd("taskkill /IM chrome.exe");
				
			}else if(browserStatus==2){
				//杀掉windows进程中的Firefox浏览器进程，关闭所有Firefox浏览器
			       WindowsUtils.killByName("firefox.exe");
			       Vpn.executeCmd("taskkill /IM firefox.exe");
			}else if(browserStatus==3){
				 //杀掉windows进程中的Firefox浏览器进程，关闭所有iexplore浏览器
			       WindowsUtils.killByName("iexplore.exe");
			       Vpn.executeCmd("taskkill /IM iexplore.exe");
			}
			 } catch (Exception e) {
					System.out.println("出异常了*****************");
					
				}
		}
	
	

	
	
}
